#include "game.h"
#include <memory>
// 构造函数初始化
Game::Game() 
    : ruleChecker(&board, this)
    , selectedPos(-1, -1)
    , isRedTurn(true)
    , gameOverFlag(false)
    , redWonFlag(false)
    , isReturnToMenu(false)
    , isBackToExitPage(false)
    , isUndoneInCurrentTurn(false)
    , skipSaveOnDrawAgree(false)
    , isDualMode(false)
    , isAIMode(false)           // 新增
    , isReturnToMenuAI(false)   // 新增
{
    // 初始化历史记录为空
    boardHistory.clear();
    srand(time(NULL));
    // 默认使用简单AI策略
    currentAIStrategy = std::make_unique<SimpleAIStrategy>();
}
// 设置AI难度
void Game::setAIDifficulty(int difficulty) 
{
    switch (difficulty) 
    {
        case 0:
            currentAIStrategy = std::make_unique<SimpleAIStrategy>();
            std::cout << "设置AI难度：简单" << std::endl;
            break;
        case 1:
            currentAIStrategy = std::make_unique<MediumAIStrategy>();
            std::cout << "设置AI难度：中等" << std::endl;
            break;
        case 2:
            currentAIStrategy = std::make_unique<HardAIStrategy>();
            std::cout << "设置AI难度：困难" << std::endl;
            break;
        default:
            currentAIStrategy = std::make_unique<SimpleAIStrategy>();
            std::cout << "默认AI难度：简单" << std::endl;
            break;
    }
}
// 人机模式移动处理
bool Game::processAIMove(const Pos& currentPos) {
    ChessDef::pieceID currentPiece = board.getPieceAt(currentPos);
    
    // 选中阶段
    if (selectedPos.row == -1) {
        if (currentPiece != ChessDef::kong) {
            bool isCurrentRed = ChessDef::isRed(currentPiece);
            // 人机模式玩家只能选红方棋子
            if (isCurrentRed) {
                selectedPos = currentPos;
                std::cout << "选中棋子: (" << currentPos.row << "," << currentPos.col << ")" << std::endl;
                drawer.draw(board, selectedPos);
                return false; // 还未完成移动
            } else {
                std::cout << "人机模式只能选择红方棋子" << std::endl;
                return false;
            }
        } else {
            std::cout << "点击空位置" << std::endl;
            if (selectedPos.row != -1) {
                selectedPos = Pos(-1, -1);
                drawer.draw(board, selectedPos);
            }
            return false;
        }
    }
    
    // 移动阶段
    std::cout << "尝试移动: (" << selectedPos.row << "," << selectedPos.col << ")->(" 
              << currentPos.row << "," << currentPos.col << ")" << std::endl;
    
    if (ruleChecker.isValidMove(selectedPos, currentPos)) {
        BoardSnapshot snapshot = getCurrentSnapshot();
        boardHistory.push_back(snapshot);
        
        board.movePiece(selectedPos, currentPos);
        isRedTurn = false; // 切换为电脑回合
        isUndoneInCurrentTurn = false;
        
        std::cout << "移动成功，切换为电脑回合" << std::endl;
        
        // 立即刷新
        selectedPos = Pos(-1, -1);
        drawer.draw(board, selectedPos);
        return true; // 移动完成
    } else {
        std::cout << "移动无效" << std::endl;
        selectedPos = Pos(-1, -1);
        drawer.draw(board, selectedPos);
        return false;
    }
}

// 人机模式功能按钮处理
bool Game::isAIFunctionButtonClicked(const Point& touchPoint) {
    int x = touchPoint.x();
    int y = touchPoint.y();

    // 只处理返回菜单按钮
    if (x >= BTN_MENU_X && x <= BTN_MENU_X + BTN_WIDTH &&
        y >= BTN_MENU_Y && y <= BTN_MENU_Y + BTN_HEIGHT) {
        isReturnToMenuAI = true;
        std::cout << "人机模式：返回菜单" << std::endl;
        return true;
    }

    return false;
}
// 判断触摸是否落在功能按钮上
bool Game::isFunctionButtonClicked(const Point& touchPoint) 
{
    int x = touchPoint.x();
    int y = touchPoint.y();

    // 红方悔棋按钮（仅红方回合可点击）
    if (x >= BTN_REDO_X && x <= BTN_REDO_X + BTN_HEIGHT &&
        y >= BTN_REDO_Y && y <= BTN_REDO_Y + BTN_WIDTH) 
    {
        redoMove(true); // 传入true：表示点击的是红方按钮
        return true;
    }
    // 黑方悔棋按钮（仅黑方回合可点击）
    else if (x >= BTN_REDO2_X && x <= BTN_REDO2_X + BTN_HEIGHT && 
             y >= BTN_REDO2_Y && y <= BTN_REDO2_Y + BTN_WIDTH) 
    {
        redoMove(false); // 传入false：表示点击的是黑方按钮
        return true;
    }
    // 重新开局按钮
    else if (x >= BTN_RESTART_X && x <= BTN_RESTART_X + BTN_WIDTH &&
             y >= BTN_RESTART_Y && y <= BTN_RESTART_Y + BTN_HEIGHT) 
    {
        restartGame();
        return true;
    }
    // 存档按钮（复用原有saveGame）
    else if (x >= BTN_SAVE_X && x <= BTN_SAVE_X + BTN_WIDTH &&
             y >= BTN_SAVE_Y && y <= BTN_SAVE_Y + BTN_HEIGHT) 
    {
        saveGame();
        return true;
    }
    // 求和按钮（红方/黑方）
    else if ((x >= BTN_DRAW_X && x <= BTN_DRAW_X + BTN_HEIGHT &&
              y >= BTN_DRAW_Y && y <= BTN_DRAW_Y + BTN_WIDTH) ||
             (x >= BTN_DRAW2_X && x <= BTN_DRAW2_X + BTN_HEIGHT &&
              y >= BTN_DRAW2_Y && y <= BTN_DRAW2_Y + BTN_WIDTH))
    {
        requestDraw();
        return true;
    }
    // 认输按钮（红方/黑方）
    else if ((x >= BTN_GIVEUP_X && x <= BTN_GIVEUP_X + BTN_HEIGHT &&
              y >= BTN_GIVEUP_Y && y <= BTN_GIVEUP_Y + BTN_WIDTH) ||
             (x >= BTN_GIVEUP2_X && x <= BTN_GIVEUP2_X + BTN_HEIGHT &&
              y >= BTN_GIVEUP2_Y && y <= BTN_GIVEUP2_Y + BTN_WIDTH)) 
    {
        giveUp();
        return true;
    }
    // 返回菜单按钮
    else if (x >= BTN_MENU_X && x <= BTN_MENU_X + BTN_WIDTH &&
             y >= BTN_MENU_Y && y <= BTN_MENU_Y + BTN_HEIGHT) 
    {
        returnToMenu();
        return true;
    }
    // 退出游戏按钮
    else if (x >= BTN_EXIT_X && x <= BTN_EXIT_X + BTN_WIDTH &&
             y >= BTN_EXIT_Y && y <= BTN_EXIT_Y + BTN_HEIGHT) 
    {
        exitGame();
        return true;
    }

    return false; // 未点击任何功能按钮
}

//实现双机模式专用按钮处理函数（只保留返回菜单功能）
bool Game::isDualFunctionButtonClicked(const Point& touchPoint) 
{
    int x = touchPoint.x();
    int y = touchPoint.y();

    // 只处理返回菜单按钮
    if (x >= BTN_MENU_X && x <= BTN_MENU_X + BTN_WIDTH &&
        y >= BTN_MENU_Y && y <= BTN_MENU_Y + BTN_HEIGHT) 
    {
        // 双机模式返回菜单（无保存弹窗）
        tcpClient.sendData("exit"); // 通知对方退出
        isReturnToMenuDual = true;
        cout << "双机模式：返回菜单" << endl;
        return true;
    }

    return false; // 其他按钮均不响应
}

// 屏幕坐标转数组坐标
bool Game::convert(int x, int y, Pos &pos)
{
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if ((x > 175 + 50 * j - 25) && (x < 175 + 50 * j + 25) &&
                (y > 40 + 50 * i - 25) && (y < 40 + 50 * i + 25))
            {
                pos.row = i;
                pos.col = j;
                return true;
            }
        }
    }
    return false;
}

// 判断游戏是否结束
bool Game::isGameOver()
{
    if (gameOverFlag) 
    {
        return true;
    }

    // 有一方的头被吃了就算结束
    bool hasShuai = false;
    bool hasJiang = false;
    for (int row = 0; row < 9; row++)
    {
        for (int col = 0; col < 10; col++)
        {
            if (board.getPieceAt(Pos(row, col)) == ChessDef::shuai)
            {
                hasShuai = true;
            }
            if (board.getPieceAt(Pos(row, col)) == ChessDef::jiang)
            {
                hasJiang = true;
            }
        } 
    }

    return !hasShuai || !hasJiang;
}

// 设置游戏结束状态
void Game::setGameOver(bool isRedVictory) 
{
    gameOverFlag = true;    // 标记游戏结束
    redWonFlag = isRedVictory;  // 记录胜利方
    std::cout << "照面触发，游戏结束标志已设置" << std::endl;
}

// 结束返回界面
void Game::showGameOverAndReturnMenu(Touch* touch)
{
    // 结束提示
    if (gameOverFlag) 
    {
        std::cout << "游戏结束! " << (redWonFlag ? "红方胜利（黑方照面）" : "黑方胜利（红方照面）") << std::endl;
        redWonFlag ? g_draw.drawBmp("./hongwon.bmp", 0, 0) : g_draw.drawBmp("./heiwon.bmp", 0, 0);
    } 
    else 
    {
        std::cout << "游戏结束! " << (isRedTurn ? "黑方胜利" : "红方胜利") << std::endl;
        isRedTurn ? g_draw.drawBmp("./heiwon.bmp", 0, 0) : g_draw.drawBmp("./hongwon.bmp", 0, 0);
    }

    cout << "等待返回主界面" << endl;
    Point backTouch;
    touch->wait(backTouch);
}

// 游戏主循环
void Game::run()
{
    Touch* touch = Touch::instance();
    Lcd* lcd = Lcd::instance();

    while (1)
    {
        g_draw.drawBmp("./tuichu.bmp", 0, 0); 
        cout << "当前在退出页" << endl; 
        
        Point initTouch;
        touch->wait(initTouch);
        cout << "正在进入游戏" << endl;

        // 加载游戏进入画面
        g_draw.drawBmp("./jinru.bmp", 0, 0);
        Point startTouch;
        touch->wait(startTouch);

        // 判断程序是否退出
        bool isExit = false; // 菜单循环标志
        isBackToExitPage = false; // 每次进菜单前重置“回退出页”标志

        while (!isExit && !isBackToExitPage)
        {
            // 加载菜单
            g_draw.drawBmp("./caidan.bmp", 0, 0);
            cout << "等待选择菜单" << endl;

            // 等待点击
            Point menuTouch;
            touch->wait(menuTouch);

            // 获取点击坐标
            int touchX = menuTouch.x();
            int touchY = menuTouch.y();

            // 单机对战
            if (touchX >= MENU_PATTERN_X1 && touchX <= MENU_PATTERN_X2 &&
                touchY >= MENU_PATTERN1_Y1 && touchY <= MENU_PATTERN1_Y2)
            {
                cout << "选择了单机对战，开始布局" << endl;
                // 重置初始化棋盘
                board.reset();
                // 将标志位恢复初始状态
                gameOverFlag = false;
                redWonFlag = false;
                isRedTurn = true;
                isReturnToMenu = false;

                // 进入对战循环
                while (!isGameOver() && !isBackToExitPage)
                {   
                    // 更新棋盘
                    drawer.draw(board, selectedPos);
                    // 等待触发事件
                    Point touchPoint;
                    touch->wait(touchPoint);
                    // 将获取到的坐标转化为数组下标
                    Pos currentPos;
                    convert(touchPoint.x(), touchPoint.y(), currentPos);
                    // 选中并校验移动逻辑
                    handleInput(currentPos, touchPoint);
                }

                // 判断是否是主动返回菜单
                if (isReturnToMenu) 
                {
                    isReturnToMenu = false;
                    cout << "已退出对局，回到菜单" << endl;
                } 
                else if (isBackToExitPage) 
                {
                    // 直接标记退出菜单循环，回到退出页
                    isExit = true;
                    isBackToExitPage = false;
                    cout << "直接退出到退出页" << endl;
                }
                else 
                {
                    // 正常游戏结束，显示胜利界面
                    drawer.draw(board, selectedPos);
                    showGameOverAndReturnMenu(touch);
                }
            }
            // 双击对战
            else if (touchX >= MENU_PATTERN_X1 && touchX <= MENU_PATTERN_X2 &&
                    touchY >= MENU_PATTERN2_Y1 && touchY <= MENU_PATTERN2_Y2)
            {
                cout << "选择了双机对战，正在连接服务器..." << endl;
                g_draw.drawBmp("./zhengzailianjie.bmp", 0, 0);
                
                serverIp = "192.168.6.192";
                serverPort = 8888;
                if (!tcpClient.connectToServer(serverIp, serverPort)) 
                {
                    g_draw.drawBmp("./lianjieshibai.bmp", 0, 0);
                    sleep(2);
                    continue;
                }
                
                // 角色协商
                char roleBuffer[16] = {0}; 
                cout << "等待服务器分配角色..." << endl;
                ssize_t recvLen = tcpClient.recvData(roleBuffer, sizeof(roleBuffer)-1);        
                
                cout << "收到服务器分配的角色为：" << roleBuffer << endl;
                
                // 关键修正：明确的角色分配
                if (recvLen > 0 && strcmp(roleBuffer, "host") == 0) 
                {
                    isHost = true;
                    tcpClient.sendData("host_confirm");
                    g_draw.drawBmp("./nishihongfang.bmp", 0, 0);
                    cout << "我是红方（主机）" << endl;
                } 
                else 
                {
                    isHost = false;
                    tcpClient.sendData("client_confirm");
                    g_draw.drawBmp("./nishiheifang.bmp", 0, 0);
                    cout << "我是黑方（客户端）" << endl;
                }
                sleep(2);
                
                tcpClient.startRecvThread();
                tcpClient.setNonBlocking();
                
                // 准备阶段
                g_draw.drawBmp("./zhunbeijvxu.bmp", 0, 0);
                sleep(1);
                
                tcpClient.sendData("ready");
                cout << "已发送就绪信号，等待对方..." << endl;
                g_draw.drawBmp("./dengdaiduifang.bmp", 0, 0);
                
                // 等待对方就绪
                bool opponentReady = false;
                time_t startWait = time(NULL);
                while (true) 
                {
                    if (difftime(time(nullptr), startWait) > 10) 
                    {
                        g_draw.drawBmp("./duifangchaoshi.bmp", 0, 0);
                        sleep(2);
                        tcpClient.disconnect();
                        break;
                    }
                    
                    std::string recvData = tcpClient.getReceivedData();
                    if (recvData == "ready") 
                    {
                        opponentReady = true;
                        break;
                    }
                    usleep(100000);
                }
                
                if (!opponentReady) continue;
                
                // 进入对战状态 - 彻底重写回合逻辑
                isDualMode = true;
                drawer.setDualMode(true);
                
                // 重置游戏状态
                board.reset();
                gameOverFlag = false;
                redWonFlag = false;
                selectedPos = Pos(-1, -1);
                boardHistory.clear();
                isReturnToMenuDual = false;
                isUndoneInCurrentTurn = false;
                
                // 关键修正：使用统一的回合管理逻辑
                // 游戏开始时总是红方先手
                isRedTurn = true; // 红方先手
                
                cout << "对战开始 - 角色:" << (isHost ? "红方(主机)" : "黑方(客户端)") 
                    << "，当前全局回合:" << (isRedTurn ? "红方" : "黑方") << endl;
                
                // 倒计时
                g_draw.drawBmp("./daojishi3.bmp", 0, 0);
                sleep(1);
                g_draw.drawBmp("./daojishi2.bmp", 0, 0);
                sleep(1);
                g_draw.drawBmp("./daojishi1.bmp", 0, 0);
                sleep(1);
                g_draw.drawBmp("./kaishiduijv.bmp", 0, 0);
                sleep(1);
                
                // 双机对战主循环
                while (!isReturnToMenuDual && !isGameOver() && !isBackToExitPage && tcpClient.isConnectedStatus()) 
                {
                    if (!tcpClient.isConnectedStatus()) 
                    {
                        g_draw.drawBmp("./lianjiesuodie.bmp", 0, 0);
                        sleep(2);
                        isReturnToMenuDual = true;
                        break;
                    }
                    
                    // 刷新棋盘
                    drawer.draw(board, selectedPos);
                    
                    
                    // 红方回合：主机操作，客户端等待
                    // 黑方回合：客户端操作，主机等待
                    bool isMyTurn = (isHost && isRedTurn) || (!isHost && !isRedTurn);
                    
                    cout << "=== 状态更新 ===" << endl;
                    cout << "我的角色: " << (isHost ? "红方" : "黑方") << endl;
                    cout << "全局回合: " << (isRedTurn ? "红方" : "黑方") << endl;
                    cout << "是否我的回合: " << (isMyTurn ? "是" : "否") << endl;
                    cout << "=================" << endl;
                    
                    if (isMyTurn) 
                    {
                        cout << "*** 我的回合开始 ***" << endl;
                        bool turnCompleted = false;
                        
                        while (!turnCompleted && !isReturnToMenuDual && tcpClient.isConnectedStatus()) 
                        {
                            // 刷新棋盘显示
                            drawer.draw(board, selectedPos);
                            
                            Point touchPoint;
                            Touch* touch = Touch::instance();
                            
                            // 使用混合方式检测触摸
                            if (touch->check(touchPoint)) 
                            {
                                cout << "触摸坐标: (" << touchPoint.x() << "," << touchPoint.y() << ")" << endl;
                                
                                // 处理功能按钮
                                if (isDualFunctionButtonClicked(touchPoint)) 
                                {
                                    if (isReturnToMenuDual) 
                                    {
                                        tcpClient.sendData("exit");
                                        break;
                                    }
                                    continue;
                                }
                                
                                // 处理棋盘操作
                                Pos currentPos;
                                if (convert(touchPoint.x(), touchPoint.y(), currentPos)) 
                                {
                                    if (processDualMove(currentPos)) 
                                    {
                                        turnCompleted = true; // 移动成功，回合结束
                                    }
                                }
                                else 
                                {
                                    // 点击棋盘外取消选中
                                    if (selectedPos.row != -1) {
                                        selectedPos = Pos(-1, -1);
                                    }
                                }
                            }
                            else 
                            {
                                // 检查网络数据（对方可能退出）
                                std::string recvData = tcpClient.getReceivedData();
                                if (!recvData.empty() && recvData == "exit") 
                                {
                                    cout << "对方退出" << endl;
                                    g_draw.drawBmp("./duifangtuichu.bmp", 0, 0);
                                    sleep(2);
                                    isReturnToMenuDual = true;
                                    break;
                                }
                                
                                usleep(50000); // 短暂休眠
                            }
                        }
                        
                        cout << "*** 我的回合结束 ***" << endl;
                    }
                    else 
                    {
                        cout << "*** 对方回合，等待中 ***" << endl;
                        bool opponentMoveReceived = false;
                        int waitCount = 0;
                        
                        while (!opponentMoveReceived && !isReturnToMenuDual && tcpClient.isConnectedStatus()) 
                        {
                            // 定期刷新棋盘
                            if (waitCount % 10 == 0) {
                                drawer.draw(board, selectedPos);
                            }
                            
                            std::string recvData = tcpClient.getReceivedData();
                            
                            if (!recvData.empty()) 
                            {
                                cout << "收到网络数据: " << recvData << endl;
                                
                                if (recvData == "exit") 
                                {
                                    cout << "对方退出" << endl;
                                    g_draw.drawBmp("./duifangtuichu.bmp", 0, 0);
                                    sleep(2);
                                    isReturnToMenuDual = true;
                                    break;
                                }
                                
                                // 解析移动数据
                                size_t pos1 = recvData.find(',');
                                size_t pos2 = recvData.find(',', pos1+1);
                                size_t pos3 = recvData.find(',', pos2+1);
                                
                                if (pos1 != string::npos && pos2 != string::npos && pos3 != string::npos) 
                                {
                                    try 
                                    {
                                        int fromRow = stoi(recvData.substr(0, pos1));
                                        int fromCol = stoi(recvData.substr(pos1+1, pos2-pos1-1));
                                        int toRow = stoi(recvData.substr(pos2+1, pos3-pos2-1));
                                        int toCol = stoi(recvData.substr(pos3+1));
                                        
                                        Pos from(fromRow, fromCol);
                                        Pos to(toRow, toCol);
                                        
                                        cout << "执行对方移动: (" << fromRow << "," << fromCol << ")->(" << toRow << "," << toCol << ")" << endl;
                                        
                                        if (ruleChecker.isValidMove(from, to)) 
                                        {
                                            board.movePiece(from, to);
                                            isRedTurn = !isRedTurn; // 切换回合
                                            opponentMoveReceived = true;
                                            cout << "对方移动成功，回合切换为: " << (isRedTurn ? "红方" : "黑方") << endl;
                                            
                                            // 立即刷新
                                            drawer.draw(board, selectedPos);
                                        }
                                        else 
                                        {
                                            cout << "对方移动无效" << endl;
                                        }
                                    }
                                    catch (...) 
                                    {
                                        cout << "移动数据解析失败" << endl;
                                    }
                                }
                            }
                            
                            usleep(50000);
                            waitCount++;
                        }
                        
                        cout << "*** 对方回合结束 ***" << endl;
                    }
                    
                    // 检查游戏是否结束
                    if (isGameOver()) {
                        cout << "游戏结束！" << endl;
                        break;
                    }
                }
                
                // 清理
                isDualMode = false;
                drawer.setDualMode(false);
                tcpClient.disconnect();
                
                if (isReturnToMenuDual) 
                {
                    isReturnToMenuDual = false;
                    cout << "返回菜单" << endl;
                }
                else if (isGameOver()) 
                {
                    showGameOverAndReturnMenu(Touch::instance());
                }
            }
            //人机对战
            else if( touchX >= MENU_PATTERN_X1 && touchX <= MENU_PATTERN_X2 &&
                     touchY >= MENU_PATTERN3_Y1 && touchY <= MENU_PATTERN3_Y2)
            {
                cout << "选择了人机对战" << endl;

                // 显示难度选择界面
                g_draw.drawBmp("./xuanzenandu.bmp", 0, 0);
                cout << "请选择AI难度" << endl;
                
                // 等待难度选择
                Point difficultyTouch;
                bool difficultySelected = false;
                int selectedDifficulty = 0; // 默认简单
                
                while (!difficultySelected) 
                {
                    touch->wait(difficultyTouch);
                    int x = difficultyTouch.x();
                    int y = difficultyTouch.y();
                    
                    // 简单难度按钮区域
                    if (x >= 65 && x <= 235 && y >= 192 && y <= 370) 
                    {
                        selectedDifficulty = 0;
                        difficultySelected = true;
                        cout << "选择简单难度" << endl;
                    }
                    // 中等难度按钮区域  
                    else if (x >= 315 && x <= 485 && y >= 192 && y <= 370) 
                    {
                        selectedDifficulty = 1;
                        difficultySelected = true;
                        cout << "选择中等难度" << endl;
                    }
                    // 困难难度按钮区域
                    else if (x >= 565 && x <= 730 && y >= 192 && y <= 370) 
                    {
                        selectedDifficulty = 2;
                        difficultySelected = true;
                        cout << "选择困难难度" << endl;
                    }
                }
                
                // 设置AI难度
                setAIDifficulty(selectedDifficulty);
                
                // 设置人机模式
                isAIMode = true;
                drawer.setAIMode(true);
                
                // 重置游戏状态
                board.reset();
                gameOverFlag = false;
                redWonFlag = false;
                isRedTurn = true;  // 玩家为红方先手
                selectedPos = Pos(-1, -1);
                boardHistory.clear();
                isReturnToMenuAI = false;
                isUndoneInCurrentTurn = false;

                // 显示准备界面
                g_draw.drawBmp("./zhunbeijvxu.bmp", 0, 0);
                sleep(1);
                g_draw.drawBmp("./kaishiduijv.bmp", 0, 0);
                sleep(1);
                // 人机对战主循环
                while (!isReturnToMenuAI && !isGameOver() && !isBackToExitPage) {
                    // 刷新棋盘
                    drawer.draw(board, selectedPos);
                    
                    if (isRedTurn) {
                        // 玩家回合（红方）
                        cout << "玩家回合（红方）" << endl;
                        bool turnCompleted = false;
                        while (!turnCompleted && !isReturnToMenuAI) {
                            Point touchPoint;
                            Touch* touch = Touch::instance();
                            
                            if (touch->check(touchPoint)) {
                                cout << "触摸坐标: (" << touchPoint.x() << "," << touchPoint.y() << ")" << endl;
                                // 处理功能按钮
                                if (isAIFunctionButtonClicked(touchPoint)) {
                                    if (isReturnToMenuAI) {
                                        break;
                                    }
                                    continue;
                                }
                                // 处理棋盘操作
                                Pos currentPos;
                                if (convert(touchPoint.x(), touchPoint.y(), currentPos)) {
                                    if (processAIMove(currentPos)) {
                                        turnCompleted = true;
                                    }
                                } 
                                else {
                                    // 点击棋盘外取消选中
                                    if (selectedPos.row != -1) {
                                        selectedPos = Pos(-1, -1);
                                        drawer.draw(board, selectedPos);
                                    }
                                }
                            }
                            usleep(50000);
                        }
                    }                    
                    else {
                        // 电脑回合（黑方）
                        cout << "电脑回合（黑方）- " << currentAIStrategy->getStrategyName() << "AI思考中..." << endl;
                        
                        // 显示电脑思考中
                        drawer.drawBmp("./diannaosikao.bmp", 200, 120);
                        sleep(1); // 模拟思考时间
                        cout << "gameOverFlag6: "<< gameOverFlag << endl;
                        // 执行电脑走棋
                        if (currentAIStrategy->makeMove(board, ruleChecker)) {
                            cout << "gameOverFlag7: "<< gameOverFlag << endl;
                            // 切换为玩家回合
                            isRedTurn = true;
                            isUndoneInCurrentTurn = false;
                            cout << "电脑走棋完成，切换为玩家回合" << endl;
                            cout << "gameOverFlag: "<< gameOverFlag << endl;
                        } else {
                            cout << "电脑走棋失败" << endl;
                        }
                    }
                    // 检查游戏是否结束
                    if (isGameOver()) {
                        cout << "游戏结束！" << endl;
                        break;
                    }
                }
                
                // 清理
                isAIMode = false;
                drawer.setAIMode(false);
                
                if (isReturnToMenuAI) {
                    isReturnToMenuAI = false;
                    cout << "返回菜单" << endl;
                } else if (isGameOver()) {
                    showGameOverAndReturnMenu(Touch::instance());
                }
            }
            // 返回上一次对战
            else if (touchX >= MENU_PATTERN_X1 && touchX <= MENU_PATTERN_X2 &&
                     touchY >= MENU_PATTERN4_Y1 && touchY <= MENU_PATTERN4_Y2)
            {
                cout << "选择了返回上一级游戏" << endl;
                bool loadOk = loadGame("./save.txt");

                // 判断读取文件有没有成功
                if (loadOk)
                {
                    // 成功了就进入对局
                    while (!isBackToExitPage && !isGameOver())
                    {
                        drawer.draw(board, selectedPos);
                        Point touchPoint;
                        touch->wait(touchPoint);
                        Pos currentPos;
                        convert(touchPoint.x(), touchPoint.y(), currentPos);
                        handleInput(currentPos, touchPoint);
                    }

                    // 判断是否是主动返回菜单
                    if (isReturnToMenu) 
                    {
                        isReturnToMenu = false;
                        cout << "已退出对局，回到菜单" << endl;
                    } 
                    else if (isBackToExitPage) 
                    {
                        // 直接标记退出菜单循环，回到退出页
                        isExit = true;
                        cout << "直接退出到退出页" << endl;
                    }
                    else 
                    {
                        // 正常游戏结束，显示胜利界面
                        drawer.draw(board, selectedPos);
                        showGameOverAndReturnMenu(touch);
                    }
                }
                else
                {
                    cout << "读取存档失败，留在菜单" << endl;
                    // 显示读取失败图片
                    g_draw.drawBmp("./duqushibai.bmp", 0, 0);
                    sleep(2);
                }
            }
            // 退出游戏
            else if (touchX >= MENU_EXIT_X1 && touchX <= MENU_EXIT_X2 &&
                     touchY >= MENU_EXIT_Y1 && touchY <= MENU_EXIT_Y2)
            {
                cout << "选择了退出程序" << endl;
                isExit = true;  // 退出菜单循环，程序结束
            }
            else
            {
                cout << "点击菜单无效区域，重新选择..." << endl;
            }   
        }
    }
}



// 处理输入（选中和移动逻辑）
void Game::handleInput(const Pos &currentPos, const Point &touchPoint)
{
    // 优先处理功能按钮点击
    if (isFunctionButtonClicked(touchPoint)) 
    {
        return; // 已处理，无需继续
    }

    ChessDef::pieceID currentPiece = board.getPieceAt(currentPos);

    // 尝试选中己方棋子
    if (selectedPos.row == -1)
    {
        if (currentPiece != ChessDef::kong)
        {
            bool isCurrentRed = ChessDef::isRed(currentPiece);
            if (isCurrentRed == isRedTurn)
            {
                selectedPos = currentPos;
                std::cout << "选中棋子：(" << currentPos.row << "," << currentPos.col << ")" << std::endl;
            }
        }
    }
    // 已选中就尝试移动目标
    else
    {
        // 若点击的是己方另一个棋子：转移选中
        if (currentPiece != ChessDef::kong)
        {
            bool isCurrentRed = ChessDef::isRed(currentPiece);
            if (isCurrentRed == isRedTurn)
            {
                selectedPos = currentPos; // 直接切换选中目标
                return; // 不执行移动逻辑，直接返回
            }
        }

        // 判断是否合法
        if (ruleChecker.isValidMove(selectedPos, currentPos))
        {
            // 关键：移动前保存当前棋盘快照（用于悔棋）
            BoardSnapshot snapshot = getCurrentSnapshot();
            boardHistory.push_back(snapshot);

            // 合法就移动棋子
            board.movePiece(selectedPos, currentPos);

            if (gameOverFlag) 
            {
                std::cout << "移动后照面，游戏结束！" << std::endl;
            } 
            else 
            {
                isRedTurn = !isRedTurn; // 未结束才切换回合
                isUndoneInCurrentTurn = false; // 新回合重置“已悔棋标志”
                std::cout << "当前回合：" << (isRedTurn ? "红方" : "黑方") << std::endl;

                // 清理逻辑：只保留最近MAX_HISTORY次快照
                if (boardHistory.size() > MAX_HISTORY) 
                {
                    int eraseCount = boardHistory.size() - MAX_HISTORY;
                    boardHistory.erase(boardHistory.begin(), boardHistory.begin() + eraseCount);
                }
            }

            std::cout << "移动成功，当前回合：" << (isRedTurn ? "红方" : "黑方") << std::endl;
        }
        else
        {
            std::cout << "移动无效" << std::endl;
        }

        // 无论移动是否成功，都取消选中状态
        selectedPos = Pos(-1, -1);
    }  
}

// 求和
void Game::requestDraw() 
{
    // 显示求和弹窗
    drawer.drawBmp("./qingqiuqiuhe.bmp", 200, 120); 
    cout << "等待对方同意/拒绝求和" << endl;

    // 循环等待触摸：只认“同意/拒绝”，其他点击不生效
    Point waitPoint;
    while (true) 
    {  
        Touch::instance()->wait(waitPoint);
        int x = waitPoint.x();
        int y = waitPoint.y();

        // 判断是否点击“同意/拒绝”
        bool isAgree = (x >= 275 && x <= 375) && (y >= 270 && y <= 320);
        bool isRefuse = (x >= 425 && x <= 525) && (y >= 270 && y <= 320);

        // 点击正确区域退出循环
        if (isAgree || isRefuse) 
        {
            // 同意逻辑
            if (isAgree) 
            {
                g_draw.drawBmp("./tongyiqiuhe.bmp", 0, 0);
                cout << "和棋！点击返回菜单" << endl;
                Touch::instance()->wait(waitPoint); // 等待点击确认和棋
                skipSaveOnDrawAgree = true; // 标记：求和同意，跳过保存
                returnToMenu();
                skipSaveOnDrawAgree = false; // 重置标志位，不影响后续使用
            } 
            // 拒绝逻辑
            else 
            {
                drawer.drawBmp("./jvjueqiuhe.bmp", 200, 120);
                cout << "对方拒绝求和" << endl;
                sleep(2);
                drawer.draw(board, selectedPos);
            }
            break;
        }
        // 点击其他区域：重新显示弹窗，继续等待
        else 
        {
            cout << "点击无效，请选择同意/拒绝" << endl;
            drawer.drawBmp("./qingqiuqiuhe.bmp", 200, 120);
        }
    }
}

// 退出游戏
void Game::exitGame() 
{
    cout << "退出游戏，点击可重新进入游戏！" << endl;
    saveGame("./save.txt");
    isBackToExitPage = true;    
    isReturnToMenu = false;  
}

// 重新开局
void Game::restartGame() 
{
    board.reset(); // 重置棋盘
    boardHistory.clear(); // 清空历史
    selectedPos = Pos(-1, -1);
    isRedTurn = true;
    gameOverFlag = false;
    redWonFlag = false;
    cout << "重新开局！" << endl;
}

// 认输
void Game::giveUp() 
{
    gameOverFlag = true;
    redWonFlag = !isRedTurn; // 认输方失败，对方胜利
    cout << (isRedTurn ? "红方认输，黑方胜利！" : "黑方认输，红方胜利！") << endl;
}

// 返回菜单
void Game::returnToMenu() 
{
    //如果是求和同意，直接跳过保存弹窗
    if (!skipSaveOnDrawAgree)
    {
        // 显示“是否保存”弹窗
        drawer.drawBmp("./shifoubaocunjilu.bmp", 150, 90);
        Touch* touch = Touch::instance();
        Point confirmTouch;

        // 等待点击“是/否”（忽略无效点击）
        while (true) 
        {
            touch->wait(confirmTouch);
            int x = confirmTouch.x();
            int y = confirmTouch.y();

            // 点击“是”：保存后返回
            if ((x >= 290 && x <= 370) && (y >= 275 && y <= 330)) 
            {
                saveGame("./save.txt"); // 直接保存，不额外提示结果
                break;
            }
            // 点击“否”：直接返回
            else if ((x >= 430 && x <= 510) && (y >= 275 && y <= 330)) 
            {
                break;
            }
            // 无效点击
            else
                std::cout << "点击到了无效区域" << endl;
        }
    }

    // 退出当前对局循环（通过设置gameOverFlag实现）
    gameOverFlag = true;
    isReturnToMenu = true; // 点击返回而不是正常结束
    redWonFlag = false; // 不影响胜负
    cout << "返回菜单..." << endl;
}

// 生成当前棋盘的快照（复制所有棋子+记录当前回合）
BoardSnapshot Game::getCurrentSnapshot() 
{
    BoardSnapshot snapshot;
    // 复制棋盘每一个位置的棋子
    for (int row = 0; row < 9; row++) 
    {
        for (int col = 0; col < 10; col++) 
        {
            snapshot.boardData[row][col] = board.getPieceAt(Pos(row, col));
        }
    }
    // 记录当前是红方还是黑方的回合
    snapshot.isRedTurn = isRedTurn;
    return snapshot;
}

// 从快照恢复棋盘状态（覆盖当前棋盘）
void Game::restoreFromSnapshot(const BoardSnapshot& snapshot) 
{
    for (int row = 0; row < 9; row++) 
    {
        for (int col = 0; col < 10; col++) 
        {
            board.setPieceAt(Pos(row, col), snapshot.boardData[row][col]);
        }
    }
    // 注意：回合不需要恢复，因为悔棋前已校验“当前回合=快照回合”
}

// 悔棋
void Game::redoMove(bool isRedButtonClicked) 
{
    // 先判断点击的按钮是否属于当前回合方（比如红方回合点黑方按钮，直接拦截）
    bool isCurrentPlayerRed = isRedTurn;
    if ((isRedButtonClicked && !isCurrentPlayerRed) || (!isRedButtonClicked && isCurrentPlayerRed))
    {
        cout << "只能点击自己的悔棋按钮！" << endl;
        drawer.draw(board, selectedPos);
        drawer.drawBmp("./zijihuihehuiqi.bmp", 200, 120); // 新增“按钮不匹配”提示图
        sleep(2);
        drawer.draw(board, selectedPos);
        return;
    }

    // 剥离所有“对方标签的快照”，直到找到自己的快照或记录为空
    BoardSnapshot targetSnapshot; // 目标快照（自己回合的）
    bool foundTarget = false;
    while (!boardHistory.empty()) 
    {
        // 获取当前最新快照
        BoardSnapshot lastSnapshot = boardHistory.back();
        // 判断快照标签是否与当前回合方一致（自己的快照）
        if (lastSnapshot.isRedTurn == isCurrentPlayerRed) 
        {
            targetSnapshot = lastSnapshot;
            foundTarget = true;
            break; // 找到自己的快照，停止剥离
        } 
        else 
        {
            // 是对方的快照，剥离（删除）
            boardHistory.pop_back();
            cout << "剥离对方快照，继续查找..." << endl;
        }
    }

    // 没找到自己的快照（比如没走棋），拦截
    if (!foundTarget) 
    {
        cout << "没有可悔的步骤！" << endl;
        drawer.draw(board, selectedPos);
        drawer.drawBmp("./meiyouhuiqijilu.bmp", 200, 120);
        sleep(2);
        drawer.draw(board, selectedPos);
        return;
    }

    // 判断当前回合是否已悔棋（单次限制）
    if (isUndoneInCurrentTurn) 
    {
        cout << "当前回合已悔棋，不可连续操作！" << endl;
        drawer.draw(board, selectedPos);
        drawer.drawBmp("./bunenglianxuhuiqi.bmp", 200, 120);
        sleep(2);
        drawer.draw(board, selectedPos);
        return;
    }

    // 执行悔棋（恢复到自己的快照）
    restoreFromSnapshot(targetSnapshot);
    boardHistory.pop_back(); // 删除已恢复的自己的快照
    isUndoneInCurrentTurn = true; // 标记已悔棋

    // 成功反馈
    drawer.drawBmp("./huiqichenggong.bmp", 200, 120);
    sleep(1);
    cout << "悔棋成功！当前仍为" << (isCurrentPlayerRed ? "红方" : "黑方") << "回合" << endl;
    drawer.draw(board, selectedPos);
}

// 存档
bool Game::saveGame(const string& filename)
{
    // 以覆盖以及文本的形式打开
    ofstream saveFile(filename, ios::out | ios::trunc);
    if (!saveFile.is_open())
    {
        cerr << "[错误] 无法打开存档文件：" << filename << endl;
        return false;
    }

    saveFile << "棋盘状态（9行×10列，0表示空）：" << endl;
    // 保存当前棋盘状态
    for (int row = 0; row < 9; row++)
    {
        for (int col = 0; col < 10; col++)
        {
            ChessDef::pieceID piece = board.getPieceAt(Pos(row, col));
            // 写入
            saveFile << piece << " ";
        }
        saveFile << endl;
    }

    // 写入状态（当前回合、是否结束、胜利方）
    saveFile << "当前回合（1=红方，0=黑方）:" << isRedTurn << endl;
    saveFile << "游戏是否结束（1=是，0=否）:" << gameOverFlag << endl;
    saveFile << "红方是否胜利（1=是，0=否）:" << redWonFlag << endl;

    // 关闭文件
    saveFile.close();
    // 存档成功
    cout << "存档成功，保存到了" << filename << endl;
    return true;
}

// 读档
bool Game::loadGame(const string& filename)
{
    // 打开存档
    ifstream loadFile(filename);
    if (!loadFile.is_open())
    {
        cerr << "错误：无法打开读档文件 " << filename << endl;
        return false;
    }

    // 储存读取到的一行的数据
    string tempLine;
    // 跳过第一行
    getline(loadFile, tempLine);

    // 读取棋盘数据
    for (int row = 0; row < 9; row++) 
    {
        // 读取当前行的棋子数据
        getline(loadFile, tempLine);
        // 用字符串流分割行中的数字
        stringstream ss(tempLine);

        int pieceInt;  // 存储单个棋子ID

        for (int col = 0; col < 10; col++) 
        {
            // 从行中提取一个棋子ID
            ss >> pieceInt;
            // 调用Board的setPieceAt方法，恢复当前格子的棋子
            board.setPieceAt(Pos(row, col), pieceInt);
        }
    }

    // 读取当前回合
    getline(loadFile, tempLine);
    auto colonPos = tempLine.find(':');
    if (colonPos != string::npos) 
    {
        string turnStr = tempLine.substr(colonPos + 1);
        // 字符串转bool型
        isRedTurn = (stoi(turnStr) == 1);  // 1→红方，0→黑方
    }

    // 读取游戏结束标志
    getline(loadFile, tempLine);
    colonPos = tempLine.find(':');
    if (colonPos != string::npos) 
    {
        string overStr = tempLine.substr(colonPos + 1);
        // 字符串转bool型
        gameOverFlag = (stoi(overStr) == 1);
    }

    // 读取胜利标志
    getline(loadFile, tempLine);
    colonPos = tempLine.find(':');
    if (colonPos != string::npos) 
    {
        string redWinStr = tempLine.substr(colonPos + 1);
        redWonFlag = (stoi(redWinStr) == 1);
    }

    // 关闭文件，刷新屏幕
    loadFile.close();
    // 避免留下选中状态
    selectedPos = Pos(-1, -1);
    cout << "成功：读档完成！当前回合：" << (isRedTurn ? "红方" : "黑方") << endl;
    return true;
}